<?php

namespace Beerus\Modules\BizAd\Controllers;

use App\Admin\Extensions\WorkContent;
use App\Http\Controllers\Controller;
use App\Pockets\GridDataModel;
use Biz\cache\bizAd\CtrWhite;
use Biz\model\bizAd\AdPlan as mAdPlan;
use Biz\model\bizAd\AdPlanDataFlow as mAdPlanDataFlow;
use Biz\model\bizAd\AdPlanFlowRate as mAdPlanFlowRate;
use Biz\model\bizAd\AdPrice as mAdPrice;
use Biz\model\bizAd\AdRechargeOrder;
use Biz\model\bizAd\AdWallet;
use Biz\model\bizAd\AdWalletLog;
use Biz\model\brand\Brand;
use Biz\pockets\constInterface\BizAd as iBizAd;
use Biz\pockets\excel\DownExcel;
use Biz\service\bizAd\AdBizExport;
use Biz\service\bizAd\AdPlan;
use Biz\service\bizAd\AdRechargeOrder as sAdRechargeOrder;
use Biz\service\bizAd\AdUser;
use Biz\service\bizAd\AdWallet as sAdWallet;
use Doraemon\model\ContentSignExtend;
use Doraemon\model\Flow\FlowPackage as mFlowPackage;
use Doraemon\model\Member;
use Doraemon\service\User;
use Doraemon\tools\BlockType;
use Doraemon\tools\Hhzurl;
use Doraemon\tools\IdParse;
use Doraemon\tools\Log;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Grid\Displayers\Actions;
use Encore\Admin\Layout\Column;
use Encore\Admin\Layout\Content;
use Encore\Admin\Layout\Row;
use Encore\Admin\Widgets\Form;
use Encore\Admin\Widgets\Table;
use Illuminate\Http\Request;
use Illuminate\Support\MessageBag;

class BizAdController extends Controller
{
    const PAGE_SIZE = 20;

    const UTYPE_BRAND = 1;

    /**
     * 获取订单列表
     * @param Request $request
     * @param Content $content
     * @return Content
     */
    public function orderList(Request $request, Content $content): Content
    {
        $request_data = $request->all();

        $page_size = $request->input("per_page", self::PAGE_SIZE);

        $page = $request->input("page", 1);

        $condition = [
            'order_status' => AdRechargeOrder::ORDER_STATUS_FINISHED,
        ];

        if (!empty($request_data['dsn'])) {
            $condition['dsn'] = $request_data['dsn'];
        }

        if (!empty($request_data['uid'])) {
            $condition['uid'] = $request_data['uid'];
        }

        if (is_numeric($request_data['utype'])) {
            $condition['utype'] = $request_data['utype'];
        }

        if (!empty($request_data['pay_platform'])) {
            $condition['pay_platform'] = $request_data['pay_platform'];
        }

        if (!empty($request_data['pay_time']['start'])) {
            $condition['pay_time[>=]'] = strtotime($request_data['pay_time']['start']);
        }

        if (!empty($request_data['pay_time']['end'])) {
            $condition['pay_time[<=]'] = strtotime($request_data['pay_time']['end']);
        }

        $condition['ORDER'] = ['id' => 'DESC'];
        $condition['LIMIT'] = [
            ($page - 1) * $page_size,
            $page_size
        ];

        $lists = AdRechargeOrder::dataSelect($condition);

        $total = 0;

        if (!empty($lists)) {
            unset($condition['ORDER']);
            unset($condition['LIMIT']);
            $total = AdRechargeOrder::dataCount($condition);
        }

        $uids = empty($lists) ? [] : array_column($lists, 'uid');

        $users = AdUser::formatUserInfo($uids);

        $users = $users ?? [];

        foreach ($lists as $key => $row) {
            $user = $users[$row['uid']] ?? [];
            $lists[$key]['bname'] = empty($user) ? '' : $user['bname'];
            $lists[$key]['bid'] = empty($user) ? '' : $user['bid'];
            $lists[$key]['nick'] = empty($user) ? '' : $user['nick'];
        }

        $search_params = http_build_query($condition);

        $gridModel = new GridDataModel($lists, $total, [
            'perPage' => $page_size
        ]);
        $grid = Admin::grid($gridModel, function (Grid $grid) use ($gridModel, $search_params) {
            $grid->filter(function ($filter) {
                $filter->disableIdFilter();
                $filter->column(1 / 3, function ($filter) {
                    $filter->equal('dsn', '订单编号')->placeholder('请输入订单编号');
                });
                $filter->column(1 / 3, function ($filter) {
                    $filter->equal('uid', 'UID')->placeholder('请输入用户uid');
                });
                $filter->column(1 / 3, function ($filter) {
                    $filter->equal('utype', '用户类型')->select(iBizAd::AD_UTYPES);
                });
                $filter->column(1 / 3, function ($filter) {
                    $filter->equal('pay_platform', '支付方式')->radio(AdRechargeOrder::PAY_PLATFORM);
                });
                $filter->column(2 / 3, function ($filter) {
                    $filter->between('pay_time', '支付时间')->datetime();
                });
                $filter->expand();
            });

            $grid->disableCreateButton();
            $grid->disableRowSelector();
            $grid->disableActions();
            $grid->disableExport();

            $downloadUrl = url('/admin/BizAd/account/exportOrder?' . $search_params);

            $grid->tools(function ($tools) use ($downloadUrl) {

                $tools->append('<div class="btn-group download" style="margin-right: 10px">
    <a class="btn btn-sm btn-twitter" href="' . url('/admin/BizAd/account/recharge') . '" title="代充值"><i class="fa fa-money"></i><span class="hidden-xs"> 代充值</span></a>
</div>');

                $button = '<div class="btn-group download" style="margin-right: 10px">
    <a class="btn btn-sm btn-twitter" target="_blank" title="导出" href="' . $downloadUrl . '"><i class="fa fa-download"></i><span class="hidden-xs"> 导出</span></a>
</div>';
                $tools->append($button);
            });

            $grid->column('dsn', '订单号');
            $grid->column('uid', 'UID');
            $grid->column('bname', '商家名称');
            $grid->column('bid', '商家ID');
            $grid->column('utype', '商家类型')->display(function () {
                return iBizAd::AD_UTYPES[$this->utype] ?? '';
            });
            $grid->column('price', '充值金额');
            $grid->column('pay_time', '支付时间')->display(function () {
                if (empty($this->pay_time)) {
                    return '';
                }
                return date('Y-m-d H:i:s', $this->pay_time);
            });
            $grid->column('pay_platform', '支付方式')->display(function () {
                if (empty($this->pay_platform)) {
                    return '';
                }
                return AdRechargeOrder::PAY_PLATFORM[$this->pay_platform];
            });
            $grid->column('other_sn', '第三方交易流水号');
            $grid->column('amount', '实付金额');
            $grid->column('admin_id', '操作人')->display(function () {
                if (!$this->admin_id) {
                    return '-';
                } else {
                    return Admin::user()->find($this->admin_id)->name;
                }
            })->width(60);
            $grid->column('remark', '描述');
        });

        $content->row($grid);

        return $content
            ->header('广告充值订单')
            ->description(' ')
            ->breadcrumb(['text' => '广告充值订单', 'url' => '/BizAd/account/orders']);
    }


    public function exportOrder(Request $request)
    {
        $request_data = $request->all();

        $condition = [
            'order_status' => AdRechargeOrder::ORDER_STATUS_FINISHED,
        ];

        if (!empty($request_data['dsn'])) {
            $condition['dsn'] = $request_data['dsn'];
        }

        if (!empty($request_data['uid'])) {
            $condition['uid'] = $request_data['uid'];
        }

        if (!empty($request_data['pay_platform'])) {
            $condition['pay_platform'] = $request_data['pay_platform'];
        }

        if (!empty($request_data['pay_time']['>='])) {
            $condition['pay_time[>=]'] = $request_data['pay_time']['>='];
        }

        if (!empty($request_data['pay_time']['<='])) {
            $condition['pay_time[<=]'] = $request_data['pay_time']['<='];
        }

        $lists = AdRechargeOrder::dataSelect($condition);

        if (empty($lists)) {
            $success = new MessageBag([
                'title' => '暂无查询数据导出'
            ]);

            return back()->with(compact('success'));
        } else {
            $data = [];

            $uids = empty($lists) ? [] : array_column($lists, 'uid');
            $userList = User::getBatchBasicUserInfo($uids);
            $userList = $userList ? array_column($userList, null, 'uid') : [];

            foreach ($lists as $item) {
                $data[] = [
                    'dsn' => $item['dsn'],
                    'utype' => iBizAd::AD_UTYPES[$item['utype']],
                    'uid' => $item['uid'],
                    'nick' => isset($userList[$item['uid']]) ? $userList[$item['uid']]['nick'] : ' - ',
                    'pay_time' => date('Y-m-d H:i:s', $item['pay_time']),
                    'pay_platform' => AdRechargeOrder::PAY_PLATFORM[$item['pay_platform']],
                    'other_sn' => $item['other_sn'],
                    'product_price' => $item['price'],
                    'amount' => $item['amount'],
                ];
            }

            // 设置列宽
            $header = [
                '订单号',
                '用户类型',
                'UID',
                '用户昵称',
                '支付时间',
                '支付方式',
                '第三方交易流水号',
                '订单金额',
                '实付金额',
            ];

            $excel_obj = new DownExcel();
            $excel_obj->setFileName('充值订单表 - ' . date('YmdHis'));
            $excel_obj->setSheetTitle('充值订单表');

            $widths = [
                'A' => 20,
                'B' => 22,
                'C' => 12,
                'D' => 25,
                'E' => 25,
                'F' => 30,
                'G' => 30,
                'H' => 15,
            ];

            $excel_obj->setWidth($widths);
            $excel_obj->setDefaultStyleAlignment();

            $excel_obj->create($data, $header);
        }
    }

    /**
     * 代充值
     * @param Request $request
     * @param Content $content
     * @return Content
     */
    public function recharge(Request $request, Content $content): Content
    {
        $payWays = [
            AdRechargeOrder::PAY_PLATFORM_ALI_PAY => '支付宝',
            AdRechargeOrder::PAY_PLATFORM_WE_CHAT => '微信',
            AdRechargeOrder::PAY_PLATFORM_BANK => '银行转账'
        ];

        $form = new Form();

        $form->select('utype', '用户类型')->setWidth(2,
            2)->options(iBizAd::AD_UTYPES)->default(iBizAd::UTYPE_BRAND)
            ->when('=', iBizAd::UTYPE_BRAND, function (Form $form) {
                $brands = Brand::select('*', ['uid[>]' => 0, 'status' => Brand::STATUS_USING, 'package_id[>]' => 0]);
                $brandNames = $brands ? array_column($brands, null, 'uid') : [];
                foreach ($brandNames as $uid => $row) {
                    $brandNames[$uid] = $row['brand_name'] . " [ID:{$row['id']}]" . " [UID:{$row['uid']}]";
                }
                $form->select('brand_uid', '品牌用户')->options($brandNames)->setWidth(3, 2);
            })
            ->when('=', iBizAd::UTYPE_DESIGNER, function (Form $form) {
                $form->text('designer_uid', '设计师UID')->setWidth(2, 2);
            })
            ->when('=', iBizAd::UTYPE_STORE, function (Form $form) {
                $form->text('store_uid', '门店UID')->setWidth(2, 2);
            })
            ->when('=', iBizAd::UTYPE_COMMMON, function (Form $form) {
                $form->text('uid', 'UID')->setWidth(2, 2);
            })->required();
        $form->decimal('amount', '支付金额')->setWidth(2, 2)->required();
        $form->select('pay_platform', '付款类型')->options($payWays)->setWidth(2, 2)->required();;
        $form->text('other_sn', '交易流水号')->setWidth(4, 2)->required('不能为空');
        $form->imgUpload('trade_proof', '交易凭证')->help("<span style='color: red'>交易凭证必传</span>");
        $form->action('/admin/BizAd/account/doRecharge');
        $form->confirm("确定充值？");
        return $content
            ->header('添加充值订单')
            ->breadcrumb(
                ['text' => '充值订单管理 ', 'url' => '/BizAd/account/orders'],
                ['text' => '添加充值订单'],
            )
            ->body($form->render());
    }

    //充值
    public function doRecharge(Request $request)
    {
        $params = $request->all();

        try {

            $utype = $params['utype'];

            $uid = 0;

            switch ($utype) {
                case iBizAd::UTYPE_BRAND:
                    if (empty($params['brand_uid'])) {
                        throw new \Exception('未选择品牌用户');
                    }
                    $uid = $params['brand_uid'];
                    break;
                case iBizAd::UTYPE_STORE:
                    if (empty($params['store_uid'])) {
                        throw new \Exception('UID必填！');
                    }
                    $uid = $params['store_uid'];
                    break;
                case iBizAd::UTYPE_DESIGNER:
                    if (empty($params['designer_uid'])) {
                        throw new \Exception('UID必填！');
                    }
                    $uid = $params['designer_uid'];
                    break;
                case iBizAd::UTYPE_COMMMON:
                    if (empty($params['uid'])) {
                        throw new \Exception('UID必填！');
                    }
                    $uid = $params['uid'];
                    break;
            }

            if (empty($uid)) {
                throw new \Exception('参数错误');
            }

            if (empty($params['amount'])) {
                throw new \Exception('充值金额不能为空！');
            }

            if (empty($params['other_sn'])) {
                throw new \Exception('交易流水号不能为空！');
            }

            if (empty($params['trade_proof'])) {
                throw new \Exception('交易凭证不能为空！');
            }

            $tradeProof = $params['trade_proof'];

            $user = User::getBasicUserInfo($uid);

            if (!$user) {
                throw new \Exception('uid不存在！');
            }

            if ($utype != $user['type']) {
                throw new \Exception('用户类型不匹配！');
            }

            $platform = $params['pay_platform'];

            $amount = $params['amount'];

            $adminId = Admin::user()->id;

            [$dsn, $expireTime] = sAdRechargeOrder::createOrder($uid, $utype, '广告充值', $platform, $amount,
                '运营代充值', $adminId);

            if (!$dsn) {
                throw new \Exception('创建代充值订单失败');
            }

            $orderUpdate = [
                'dsn' => $dsn,
                'other_sn' => $params['other_sn'],
                'pay_status' => AdRechargeOrder::PAY_STATUS_PAID,
                'pay_time' => time(),
                'pay_platform' => $platform,
                'amount' => $amount,
                'order_status' => AdRechargeOrder::ORDER_STATUS_FINISHED,
                'trade_proof' => $tradeProof,
            ];

            $result = sAdWallet::recharge($uid, $utype, $amount, $adminId, AdWalletLog::OP_UID_TYPE_OP, $orderUpdate);

            if (!$result) {
                throw new \Exception('代充值操作失败，请联系开发人员');
            }

            $success = new MessageBag([
                'title' => '添加代充值订单成功'
            ]);

            return redirect('/admin/BizAd/account/orders')->with(compact('success'));

        } catch (\Exception $e) {

            Log::error($e->getMessage(), $params);

            $error = new MessageBag([
                'title' => $e->getMessage()
            ]);

            return back()->with(compact('error'));
        }

    }

    /**
     * 提现
     * @param Request $request
     * @param Content $content
     * @param int $utype
     * @param int $uid
     * @return Content
     */
    public function cashout(Request $request, Content $content, int $utype, int $uid): Content
    {
        $users = AdUser::formatUserInfo([$uid]);

        $user = isset($users[$uid]) ? $users[$uid] : [];

        $bname = $user['bname'] ?? '';

        $bid = $user['bid'] ?? '';

        $wallet = sAdWallet::getWallet($uid);

        if (!$wallet) {
            return $content->header('充值余额提现')->withError('用户未充值，不允许进行提现操作！');
        }

        $form = new Form();
        $form->hidden('utype', $utype)->default($utype);
        $form->text('uid', '用户UID')->setWidth(4, 2)->default($uid)->readonly();
        $form->display('bname', '商家名称')->setWidth(4, 2)->default($bname)->readonly();
        $form->display('bid', '商家ID')->setWidth(4, 2)->default($bid)->readonly();
        $form->display('utype', '商家类型')->setWidth(4, 2)->default(iBizAd::AD_UTYPES[$utype])->readonly();
        $form->display('balance', '账户余额')->setWidth(4, 2)->default($wallet['balance']);
        $form->decimal('amount', '提现金额')->setWidth(6, 2)->required();
        $form->text('other_sn', '交易流水号')->setWidth(4, 2)->required('不能为空');
        $form->action('/admin/BizAd/wallet/doCashout');
        $form->confirm('正在为用户[' . $uid . ']提现，请仔细核对，确认后点击提交');
        return $content
            ->header('充值余额提现')
            ->breadcrumb(
                ['text' => '广告账户 ', 'url' => '/BizAd/account/balances'],
                ['text' => '充值余额提现'],
            )
            ->body($form->render());
    }


    //提现
    public function doCashout(Request $request)
    {
        $params = $request->all();

        try {

            if (empty($params['amount'])) {
                throw new \Exception('提现金额不能为空!');
            }

            if (empty($params['other_sn'])) {
                throw new \Exception('交易流水号不能为空!');
            }

            $uid = $params['uid'];

            $user = User::getBasicUserInfo($uid);

            if (!$user) {
                throw new \Exception('UID不存在!');
            }

            $utype = $user ? $user['type'] : $params['utype'];

            $amount = $params['amount'];

            $balance = sAdWallet::getBalance($uid);

            if ($amount > $balance) {
                throw new \Exception('余额不足');
            }

            $adminId = Admin::user()->id;

            $result = sAdWallet::cashOut($uid, $utype, $amount, $adminId, $params['other_sn']);

            if (!$result) {
                throw new \Exception('提现操作失败，请联系开发人员');
            }

            $success = new MessageBag([
                'title' => '提现成功'
            ]);

            return redirect('/admin/BizAd/account/balances?uid=' . $uid)->with(compact('success'));

        } catch (\Exception $e) {

            Log::error($e->getMessage(), $params);

            $error = new MessageBag([
                'title' => $e->getMessage()
            ]);

            return back()->with(compact('error'));
        }

    }


    public function brandBalance(Request $request, Content $content): Content
    {

        Admin::script($this->setScript());

        $request_data = $request->all();

        $page_size = $request->input("per_page", self::PAGE_SIZE);

        $page = $request->input("page", 1);

        $condition['data_status'] = AdWallet::STATUS_NORMAL;

        if (!empty($request_data['uid'])) {
            $condition['uid'] = $request_data['uid'];
        }

        if (!empty($request_data['utype'])) {
            $condition['utype'] = $request_data['utype'];
        }

        $condition['ORDER'] = ['id' => 'ASC'];

        $condition['LIMIT'] = [
            ($page - 1) * $page_size,
            $page_size
        ];

        $lists = AdWallet::dataSelect($condition);

        $uids = empty($lists) ? [] : array_column($lists, 'uid');

        $users = AdUser::formatUserInfo($uids);

        $users = $users ?? [];

        foreach ($lists as $key => $row) {
            $user = $users[$row['uid']] ?? [];
            $lists[$key]['bname'] = empty($user) ? '' : $user['bname'];
            $lists[$key]['bid'] = empty($user) ? '' : $user['bid'];
            $lists[$key]['nick'] = empty($user) ? '' : $user['nick'];
        }

        unset($condition['LIMIT']);

        $total = AdWallet::dataCount($condition);

        $gridModel = new GridDataModel($lists, $total, [
            'perPage' => $page_size
        ]);

        $grid = Admin::grid($gridModel, function (Grid $grid) use ($gridModel) {
            $grid->filter(function ($filter) {
                $filter->disableIdFilter();
                $filter->column(1 / 2, function ($filter) {
                    $filter->equal('uid', 'UID')->placeholder('请输入用户uid');
                });
                $filter->expand();
            });
            $grid->disableCreateButton();
            $grid->disableRowSelector();
            $grid->disableExport();

            $grid->tools(function ($tools) {
                $button = '<div class="btn-group download" style="margin-right: 10px">
    <a class="btn btn-sm btn-twitter" title="导出" href="javascript:void(0);" onclick=""><i class="fa fa-download"></i><span class="hidden-xs"> 导出报表</span></a>
</div>';
                $tools->append($button);
            });

            $grid->column('uid', 'UID');
            $grid->column('bname', '商家名称');
            $grid->column('bid', '商家ID');
            $grid->column('utype', '商家类型')->display(function () {
                return iBizAd::AD_UTYPES[$this->utype] ?? '';
            });
            $grid->column('balance', '账户余额');
            $grid->column('lock_amount', '在途金额');
            $grid->setActionClass(Actions::class);
            $grid->actions(function (Grid\Displayers\Actions $actions) {
                $actions->disableView();
                $actions->disableEdit();
                $actions->disableDelete();
                if ($actions->row->balance > 0) {
                    $linkUrl = '/admin/BizAd/wallet/cashout/' . $actions->row->utype . '/' . $actions->row->uid;
                    $html_cashout = ' <a class="fa fa-credit-card" data-id="' . $actions->row->uid . '" href="' . $linkUrl . '" style="margin-right: 5px">
                                    <span class="glyphicon" aria-hidden="true">提现</span></a>';
                    $actions->append($html_cashout);
                }
                $linkDetailUrl = '/admin/BizAd/wallet/bills/' . $actions->row->id;
                $html_detail = '<a class="fa fa-list" data-id="' . $actions->row->id . '" href="' . $linkDetailUrl . '" style="margin-left: 15px">
                                    <span class="glyphicon" aria-hidden="true">账户明细</span></a>';
                $actions->append($html_detail);

            });

        });

        $content->row($grid);

        return $content
            ->header('广告账户')
            ->description(' ')
            ->breadcrumb(['text' => '广告账户', 'url' => '/BizAd/account/balances']);

    }

    public function accountBills(Request $request, Content $content, int $walletId)
    {

        $params = $request->all();

        $page_size = $request->input("per_page", self::PAGE_SIZE);

        $page = $request->input("page", 1);

        $wallet = AdWallet::dataSelectInfo(['id' => $walletId]);

        $where['uid'] = $wallet['uid'];

        if (isset($params['op_type']) && $params['op_type']) {
            $where['op_type'] = $params['op_type'];
        } else {
            $where['op_type'] = [
                AdWalletLog::OP_TYPE_RECHARGE,
                AdWalletLog::OP_TYPE_CONSUME,
                AdWalletLog::OP_TYPE_REFUND,
                AdWalletLog::OP_TYPE_CASHOUT,
                AdWalletLog::OP_TYPE_RELEASE_LOCK_AMOUNT,
            ];
        }

        if (isset($params['date_time']) && !empty($params['date_time'])) {
            if (isset($params['date_time']['start']) && $params['date_time']['start']) {
                $where['create_time[>]'] = $params['date_time']['start'];
            }
            if (isset($params['date_time']['end']) && $params['date_time']['end']) {
                $where['create_time[<=]'] = $params['date_time']['end'];
            }
        }

        $where['ORDER'] = ['id' => 'DESC'];

        $totalCount = AdWalletLog::dataCount($where);

        $where['LIMIT'] = [($page - 1) * $page_size, $page_size];

        $lists = self::billList($where);

        $uids = [];

        foreach ($lists as $key => $v) {
            if (AdWalletLog::OP_UID_TYPE_USER == $v['op_uid_type']) {
                if (in_array($v['op_type'], [AdWalletLog::OP_TYPE_RECHARGE, AdWalletLog::OP_TYPE_CONSUME])) {
                    $uids[] = $v['op_uid'];
                } else {
                    $lists[$key]['op_uid_type'] = 0;
                }
            }
        }

        $uids = array_unique($uids);

        $users = !empty($uids) ? User::getBatchBasicUserInfo($uids) : [];

        $users = empty($users) ? [] : array_column($users, null, 'uid');

        $gridModel = new GridDataModel($lists, $totalCount, [
            'perPage' => $page_size
        ]);

        if (isset($params['page'])) {
            unset($params['page']);
        }

        if (isset($params['per_page'])) {
            unset($params['per_page']);
        }

        $search_params = http_build_query($params);

        $grid = Admin::grid($gridModel, function (Grid $grid) use ($gridModel, $users, $walletId, $search_params) {
            $grid->filter(function ($filter) {
                $filter->disableIdFilter();
                $filter->column(1 / 2, function ($filter) {
                    $filter->between('date_time', '时间范围')->datetime();
                });
                $filter->column(1 / 2, function ($filter) {
                    $filter->equal('op_type', '交易类型')->select(AdWalletLog::OP_TYPES);
                });
                $filter->expand();
            });
            $grid->disableCreateButton();
            $grid->disableRowSelector();
            $grid->disableExport();

            $downloadUrl = url('/admin/BizAd/wallet/bills/' . $walletId . '/export?' . $search_params);

            $grid->tools(function ($tools) use ($downloadUrl) {
                $button = '<div class="btn-group download" style="margin-right: 10px">
    <a class="btn btn-sm btn-twitter" target="_blank" title="导出明细" href="' . $downloadUrl . '"><i class="fa fa-download"></i><span class="hidden-xs"> 导出明细</span></a>
</div>';
                $tools->append($button);
            });

            $grid->column('version', '流水号');
            $grid->column('uid', 'UID');
            $grid->column('create_time', '时间');
            $grid->column('op_type', '交易类型')->display(function ($op_type) {
                return AdWalletLog::OP_TYPES[$op_type] ?? '';
            });
            $grid->column('remark', '摘要')->display(function ($remark) {
                return $remark . " [log id:" . $this->id . "]";
            });
            $grid->column('symbol_amount', '动账金额')->display(function ($symbol_amount) {
                if ($this->op_type == AdWalletLog::OP_TYPE_RELEASE_LOCK_AMOUNT) {
                    return '0.00';
                } else {
                    return $symbol_amount;
                }
            });
            $grid->column('balance', '余额');

            $grid->column('amount', '在途动账金额')->display(function ($amount) {
                if ($this->op_type == AdWalletLog::OP_TYPE_RELEASE_LOCK_AMOUNT) {
                    return '-' . $amount;
                } elseif ($this->op_type == AdWalletLog::OP_TYPE_CONSUME){
                    return '+' . $amount;
                }else {
                    return '0.00';
                }
            });

            $grid->column('lock_amount', '在途金额');

            $grid->column('op_uid_type', '操作人类型')->display(function ($op_uid_type) {
                $opUserTypes = AdWalletLog::OP_UID_TYPES + [0 => '平台'];
                return $opUserTypes[$op_uid_type];
            });

            $grid->column('op_uid', '操作人')->display(function ($op_uid) use ($users) {
                if ($this->op_uid_type === 0) {
                    return '系统';
                } elseif ($this->op_uid_type == AdWalletLog::OP_UID_TYPE_OP) {
                    return Admin::user()->find($op_uid)->name;
                } elseif ($this->op_uid_type == AdWalletLog::OP_UID_TYPE_USER) {
                    return isset($users[$op_uid]) ? $users[$op_uid]['nick'] : '-';
                } else {
                    return '-';
                }
            });

            $grid->column('op_rel_id', '关联信息')->display(function () {
                if ($this->op_type == AdWalletLog::OP_TYPE_RECHARGE) {
                    return "充值单号：<a href='/admin/BizAd/account/orders?&dsn=" . $this->op_rel_id . "'>" . $this->op_rel_id . "</a>";
                } elseif ($this->op_type == AdWalletLog::OP_TYPE_CASHOUT) {
                    return "提现单号：" . $this->op_rel_id;
                } else {
                    return "投放计划ID：<a href='/admin/BizAd/plan/" . $this->op_rel_id . "'>" . $this->op_rel_id . "</a>";
                }
            });

            $grid->disableActions(true);

        });

        $content->row($grid);

        return $content
            ->header('广告账户明细')
            ->description(' ')
            ->breadcrumb(
                ['text' => '广告账户', 'url' => '/BizAd/account/balances'],
                ['text' => '广告账户明细', 'url' => '/BizAd/wallet/bills/' . $walletId]
            );
    }


    private static function billList($where)
    {
        $list = AdWalletLog::dataSelect($where, [
            'id',
            'uid',
            'amount',
            'lock_amount',
            'op_rel_id',
            'op_type',
            'create_time',
            'remark',
            'version',
            'balance',
            'op_uid',
            'op_uid_type'
        ]);

        if ($list && is_array($list)) {
            foreach ($list as $key => $row) {
                $list[$key]['symbol_amount'] = AdWalletLog::SYMBOLS[$row['op_type']] . $row['amount'];
            }
        }

        return $list;
    }

    public function exportBillList(Request $request, Content $content, int $walletId)
    {

        $params = $request->all();

        $wallet = AdWallet::dataSelectInfo(['id' => $walletId]);

        $where['uid'] = $wallet['uid'];

        if (isset($params['op_type']) && $params['op_type']) {
            $where['op_type'] = $params['op_type'];
        } else {
            $where['op_type'] = [
                AdWalletLog::OP_TYPE_RECHARGE,
                AdWalletLog::OP_TYPE_CONSUME,
                AdWalletLog::OP_TYPE_REFUND,
                AdWalletLog::OP_TYPE_CASHOUT,
                AdWalletLog::OP_TYPE_RELEASE_LOCK_AMOUNT,
            ];
        }

        if (isset($params['date_time']) && !empty($params['date_time'])) {
            if (isset($params['date_time']['start']) && $params['date_time']['start']) {
                $where['create_time[>]'] = $params['date_time']['start'];
            }
            if (isset($params['date_time']['end']) && $params['date_time']['end']) {
                $where['create_time[<=]'] = $params['date_time']['end'];
            }
        }

        $where['ORDER'] = ['id' => 'DESC'];

        $lists = self::billList($where);

        $user = User::getBasicUserInfo($wallet['uid']);

        $exportData = [];

        foreach ($lists as $key => $v) {
            $exportData[$key]['version'] = $v['version'];
            $exportData[$key]['uid'] = $v['uid'];
            $exportData[$key]['create_time'] = $v['create_time'];
            $exportData[$key]['op_type'] = AdWalletLog::OP_TYPES[$v['op_type']];
            $exportData[$key]['remark'] = $v['remark'];
            $exportData[$key]['symbol_amount'] = AdWalletLog::OP_TYPE_RELEASE_LOCK_AMOUNT == $v['op_type'] ? '0.00' : $v['symbol_amount'];
            $exportData[$key]['balance'] = $v['balance'];

            if(AdWalletLog::OP_TYPE_RELEASE_LOCK_AMOUNT == $v['op_type']){
                $exportData[$key]['add_lock_amount'] = '-' . $v['amount'];
            }elseif (AdWalletLog::OP_TYPE_CONSUME == $v['op_type']){
                $exportData[$key]['add_lock_amount'] = '+' . $v['amount'];
            }else {
                $exportData[$key]['add_lock_amount'] = '0.00';
            }

            $exportData[$key]['lock_amount'] = $v['lock_amount'];
            if (AdWalletLog::OP_UID_TYPE_USER == $v['op_uid_type']) {
                if (in_array($v['op_type'], [AdWalletLog::OP_TYPE_RECHARGE, AdWalletLog::OP_TYPE_CONSUME])) {
                    $exportData[$key]['op_uid_type'] = AdWalletLog::OP_UID_TYPES[$v['op_uid_type']];
                    $exportData[$key]['op_uname'] = $wallet['uid'] == $v['uid'] ? ($user['nick'] ?? '') : '';
                } else {
                    $exportData[$key]['op_uid_type'] = '平台';
                    $exportData[$key]['op_uname'] = '系统';
                }
            } else {
                $exportData[$key]['op_uid_type'] = AdWalletLog::OP_UID_TYPES[$v['op_uid_type']] ?? '';
                if (AdWalletLog::OP_UID_TYPE_OP == $v['op_uid_type']) {
                    $exportData[$key]['op_uname'] = Admin::user()->find($v['op_uid'])->name;
                } else {
                    $exportData[$key]['op_uname'] = '';
                }
            }
            if (AdWalletLog::OP_TYPE_RECHARGE == $v['op_type']) {
                $exportData[$key]['op_rel'] = '充值单号：' . $v['op_rel_id'];
            } elseif (AdWalletLog::OP_TYPE_CASHOUT == $v['op_type']) {
                $exportData[$key]['op_rel'] = '提现单号：' . $v['op_rel_id'];
            } else {
                $exportData[$key]['op_rel'] = '投放计划ID：' . $v['op_rel_id'];
            }
        }

        $header = [
            '流水号',
            'UID',
            '时间',
            '交易类型',
            '摘要',
            '动账金额',
            '余额',
            '在途动账金额',
            '在途金额',
            '操作人类型',
            '操作人',
            '关联信息'
        ];

        $excel_obj = new DownExcel();

        $excel_obj->setFileName('账户明细表 - ' . date('YmdHis'));

        $excel_obj->setSheetTitle('账户明细表');

        $widths = [
            'A' => 12,
            'B' => 12,
            'C' => 20,
            'D' => 18,
            'E' => 30,
            'F' => 12,
            'G' => 12,
            'H' => 18,
            'I' => 12,
            'J' => 10,
            'K' => 15,
            'L' => 35,
        ];

        $excel_obj->setWidth($widths);

        $excel_obj->setDefaultStyleAlignment();

        $excel_obj->create($exportData, $header);

    }

    public function export(Request $request, $type)
    {
        try {

            $params = $request->all();

            $startDate = $params['start_date'] ?? '';

            $endDate = $params['end_date'] ?? '';

            AdBizExport::exportData($type, $startDate, $endDate);

        } catch (\Exception $e) {

            $errorMsg = '导出失败';

            $errorCode = $e->getCode();

            if (in_array($errorCode, AdBizExport::ERROR_CODE)) {
                $errorMsg = $e->getMessage();
            }

            $error = new MessageBag([
                'title' => $errorMsg
            ]);

            return redirect('/admin/BizAd/account/balances')->with(compact('error'));

        }

    }

    public function exportForm(Request $request, WorkContent $content)
    {
        Admin::script($this->setExportScript());

        $form = new Form();

        $form->attribute('class', 'adExportForm');

        $form->setWidth(10, 2);

        $beginDate = date('Y-m-01', strtotime('-1 month'));

        $endDate = date("Y-m-d", strtotime(-date('d') . 'day'));

        $form->date('start_date', '起始日期')->required()->default($beginDate);

        $form->date('end_date', '截止日期')->required()->default($endDate);

        $form->radio('etype', '类型')->options(
            [
                1 => '充值表',
                2 => '消耗表-已结束计划',
                3 => '消耗表-在途中计划',
                4 => '余额表'
            ]
        )->default(1)->required();

        $form->html('<div class="col-md-12"><div class="btn-group pull-right"><button type="button" class="btn btn-info pull-right btn-ad-export">导出</button></div></div>');

        $form->disableSubmit();

        $form->disableReset();

        return $content
            ->row($form);
    }

    private function setExportScript()
    {
        return <<<SCRIPT

        $("#app .content-header").css('display','none');
        
        $('.btn-ad-export').unbind('click').click(function(){
            var etype = $('input[name="etype"]:checked').val();
            var start_date = $('input[name="start_date"]').val();
            var end_date = $('input[name="end_date"]').val();
            if(!start_date){
                 swal('请选择起始日期', '', 'error');
                 return;
            }
            if(!end_date){
                 swal('请选择截止日期', '', 'error');
                 return;
            }
           
            let begin_stamp = moment(start_date).valueOf();
            
            let end_stamp = moment(end_date).valueOf();
            
            if(begin_stamp > end_stamp){
                 swal('选择的时间范围错误！', '', 'error');
                 return;
            }
            
            if(etype == 4){
                if(moment(start_date).format("YYYY-MM") != moment(end_date).format("YYYY-MM")){
                     swal('请选择单个月份导出余额，不能跨月！', '', 'error');
                     return;
                }
                
                if(moment(start_date).format("YYYY-MM") == moment().format("YYYY-MM")){
                     swal('当前月份余额数据尚未结算，无法导出！', '', 'error');
                     return;
                }
            }
            
            var download_url = '/admin/BizAd/account/export/'+etype+'?start_date='+start_date+'&end_date='+end_date;
                 
            const a = document.createElement('a');
    
            document.body.appendChild(a);
             
            a.style.display = 'none';
             
            a.href = download_url;
             
            a.target = '_blank';
             
            a.click();

            
        });
SCRIPT;

    }

    private function setScript()
    {
        return <<<SCRIPT
        $('.download').unbind('click').click(function(){
             layer.open({
                type: 2,
                title: '导出报表',
                shadeClose: true,
                shade: 0,
                maxmin: true,
                area: ['640px', '480px'],
                content: '/admin/BizAd/account/showExport'
            });
        });
SCRIPT;

    }


    public function planList(Request $request, Content $content): Content
    {
        Admin::script($this->setPlanScript());

        $requestAll = $request->all();

        $page_size = $request->input("per_page", self::PAGE_SIZE);

        $page = $request->input("page", 1);

        $condition = [];

        if (!empty($requestAll['id'])) {
            $condition['id'] = $requestAll['id'] ?? 0;
        }

        if (!empty($requestAll['uid'])) {
            $condition['uid'] = $requestAll['uid'] ?? 0;
        }

        if (!empty($requestAll['nick'])) {
            $uid = User::getUidByNick($requestAll['nick']);
            if ($uid) {
                $condition['uid'] = $uid;
            }
        }

        if (!empty($requestAll['plan_name'])) {
            $condition['plan_name[~]'] = $requestAll['plan_name'];
        }

        if (!empty($requestAll['plan_follow_no'])) {
            $planId = AdPlan::getPlanIdByPlanFlowNo($requestAll['plan_follow_no']);
            if ($planId) {
                $condition['id'] = $planId;
            }
        }

        if (isset($requestAll['plan_state']) && strlen($requestAll['plan_state']) > 0) {
            $condition = mAdPlan::getConditionBySettle($requestAll['plan_state']);
        }

        if (!empty($requestAll['date_time']['start'])) {
            $condition['start_time[>=]'] = strtotime($requestAll['date_time']['start']);
        }

        if (!empty($requestAll['date_time']['end'])) {
            $condition['end_time[<=]'] = strtotime($requestAll['date_time']['end']);
        }

        $condition['ORDER'] = ['start_time' => 'DESC', 'id' => 'DESC'];
        $condition['LIMIT'] = [
            ($page - 1) * $page_size,
            $page_size
        ];

        $list = mAdPlan::getPlanList($condition);
        $uids = $list ? array_column($list, 'uid') : [];

        $users = AdUser::formatUserInfo($uids);

        $objIds = $list ? array_column($list, 'obj_id') : [];

        $cSigns = $objIds ? ContentSignExtend::getExtendInfoByNoteIds($objIds) : [];

        $cSignsKv = $cSigns ? array_column($cSigns, null, 'obj_id') : [];

        foreach ($list as &$row) {
            $user = $users[$row['uid']] ?? [];
            $row['plan_no'] = AdPlan::getPlanNo($row);
            $row['bname'] = $user['bname'] ?? '';
            $row['bid'] = $user['bid'] ?? '';
            $row['nick'] = $user['nick'] ?? '';
            $row['is_display_business'] = $cSignsKv[$row['obj_id']]['is_display_business'] ?? 0;
            $preview = '';
            $objType = IdParse::getType($row['obj_id']);
            if ($objType == BlockType::TYPE_PHOTO) {
                $preview = Hhzurl::h5PhotoShow($row['obj_id']);
            } else {
                if ($objType == BlockType::TYPE_BLANK) {
                    $preview = Hhzurl::h5BlankShow($row['obj_id']);
                }
            }
            $row['preview'] = $preview;

        }

        unset($condition['LIMIT']);
        unset($condition['ORDER']);
        $total = mAdPlan::dataCount($condition);

        $gridModel = new GridDataModel($list, $total, [
            'perPage' => $page_size
        ]);
        $grid = Admin::grid($gridModel, function (Grid $grid) use ($gridModel) {
            $grid->filter(function (Grid\Filter $filter) {
                $filter->disableIdFilter();
                $filter->column(1 / 2, function (Grid\Filter $filter) {
                    $filter->dropDown('plan_value', [
                        'id' => '计划ID',
                        'plan_name' => '计划名称',
                        'plan_follow_no' => '计划加油包编号',
                    ]);
                    $filter->dropDown('user_value', [
                        'uid' => 'UID',
                        'nick' => '昵称',
                    ]);
                });
                $filter->column(1 / 2, function (Grid\Filter $filter) {
                    $filter->between('date_time', '计划时间')->datetime();
                    $planSteteOption = [
                        mAdPlan::PLAN_STATUS_NORMAL => '待投放',
                        mAdPlan::PLAN_STATUS_OPEN => '待生效',
                        mAdPlan::PLAN_STATUS_CANCEL => '已取消',
                        mAdPlan::PLAN_STATUS_START => '生效中',
                        mAdPlan::PLAN_STATUS_END => '已结束',
                        mAdPlan::PLAN_STATUS_DELETE => '已删除'
                    ];
                    $filter->equal('plan_state', '状态')->select($planSteteOption);
                });
                $filter->expand();
            });

            $grid->tools(function (Grid\Tools $tools) {
                $tools->append('<div class="btn-group download" style="margin-right: 10px">
    <a class="btn btn-sm btn-info" href="' . url('/admin/BizAd/plan/price/list') . '" title="价格配置"><i class="fa"></i><span class="hidden-xs">价格配置</span></a>
</div>');
                $tools->append('<div class="btn-group download" style="margin-right: 10px">
    <a class="btn btn-sm btn-danger" href="' . url('/admin/BizAd/plan/ctr/white') . '" title="ctr白名单"><i class="fa"></i><span class="hidden-xs">ctr白名单</span></a>
</div>');
                $tools->append('<div class="btn-group download" style="margin-right: 10px">
    <a class="btn btn-sm btn-warning" href="' . url('/admin/BizAd/plan/rate/list') . '" title="真实流量比例"><i class="fa"></i><span class="hidden-xs">真实流量比例</span></a>
</div>');
            });

            $grid->disableCreateButton();
            $grid->disableRowSelector();
            $grid->disableExport();

            $grid->fixColumns(2, -1);

            $grid->column('id', '计划ID');
            $grid->column('plan_no', '编码');
            $grid->column('bname', '商家名称');
            $grid->column('bid', '商家ID');
            $grid->column('utype', '商家身份')->display(function () {
                return iBizAd::AD_UTYPES[$this->utype] ?? '';
            });
            $grid->column('uid', 'UID');
            $grid->column('plan_name', '计划名称');
            $grid->column('start_time', '开始时间')->display(function () {
                return date('Y-m-d H:i:s', $this->start_time);
            });
            $grid->column('end_time', '结束时间')->display(function () {
                return date('Y-m-d H:i:s', $this->end_time);
            });
            $grid->column('target_count', '计划曝光');
            $grid->column('expose_count', '当前曝光');
            $grid->column('finished_rate', '进度完成');
            $grid->column('flow_rate', '真实流量比例');
            $grid->column('real_target_count', '真实计划曝光');
            $grid->column('real_expose_count', '当前真实曝光');
            $grid->column('price', '购买单价');
            $grid->column('amount', '花费')->display(function () {
                if ($this->amount > 0) {
                    $amount = $this->amount;
                } else {
                    if ($this->expose_count < $this->target_count) {
                        $amount = round(bcmul(bcdiv($this->expose_count, 1000, 3), $this->price, 3), 2);
                    } else {
                        $amount = $this->buy_amount;
                    }
                }
                return $amount;
            })->width(100);
            $grid->column('plan_state_desc', '计划状态');
            $grid->column('is_display_business', '合作标')->display(function () {
                $displayBiz = ['否', '是'];
                return $displayBiz[$this->is_display_business];
            });

            $grid->actions(function (Grid\Displayers\Actions $actions) {
                $actions->disableEdit();
                $actions->disableDelete();
                $actions->append('<a class="fa fa-file-text-o" target="" href="' . url('admin/BizAd/plan/' . $actions->row->id) . '">详情</a>');
                $actions->append('<a class="fa fa-eye preview" style="margin-left:10px;" data-preview="' . $actions->row->preview . '" href="javascript:void(0)" >查看内容</a>');
                if (!$actions->row->is_display_business) {
                    $actions->append('<a class="fa fa-tag tag-content" data-id="' . $actions->row->id . '" style="margin-left:10px;"  href="javascript:void(0)">内容打标</a>');
                }
            });

        });

        $content->row($grid);

        return $content
            ->header('投放计划列表')
            ->breadcrumb(['text' => '投放计划列表', 'url' => '/BizAd/plan/list']);
    }

    private function setPlanScript()
    {
        return <<<SCRIPT
        $('.preview').unbind('click').click(function(){
            var preview_url= $(this).data('preview');
            layer.open({                                
                type: 2,
                title: "内容预览",
                maxmin: true,
                area: ["300px", "533px"],
                content: preview_url
            });
        });

        $('.tag-content').unbind('click').click(function(){
            var id= $(this).data('id');
            let url = '/admin/BizAd/plan/' + id + '/tag';
            let params = {id:id}
            swal({
                    title: "确认给该内容打上合作标吗？",
                    type: "warning",
                    showCancelButton: true,
                    confirmButtonColor: "#DD6B55",
                    confirmButtonText: "确认",
                    showLoaderOnConfirm: true,
                    cancelButtonText: "取消",
                    preConfirm: function() {
                        $.ajax({
                            method: 'post',
                            url: url,
                            data: params,
                            success: function (e) {
                                if (e.code == 1) {
                                swal({
                                    title: e.title,
                                    type: "warning",
                                });
                                    setTimeout(function () {
                                        $.pjax.reload('#pjax-container');
                                    }, 1000);
                                } else {
                                    toastr.error(e.title, null, {
                                        timeOut : 3000
                                    }); 
                                }
                            }
                        });
          
                    }
            });
        });
       
SCRIPT;
    }

    public function planInfo(Request $request, Content $content, $id): Content
    {
        $info = mAdPlan::getPlanInfo($id);

        $userPackage = AdPlan::getUserPackage();

        $info['package_name'] = $userPackage[$info['user_package']]['package_name'];

        $info['start_time'] = date('Y-m-d H:i:s', $info['start_time']);
        $info['end_time'] = date('Y-m-d H:i:s', $info['end_time']);
        $info['settle_time'] = date('Y-m-d H:i:s', $info['settle_time']);
        $info['settle_status'] = mAdPlan::SETTLE_STATUS_MAP[$info['settle_status']];
        $user = User::getBasicUserInfo($info['uid']);
        $info['nick'] = $user['nick'] ?? '';
        $info['utype_desc'] = iBizAd::AD_UTYPES[$info['utype']];
        $info['click_rate'] = '0.00%';
        $info['click_count'] = 0;

        $top = "<div class='box' style='padding:20px 20px; display: flex;flex-direction: row; justify-content: space-between; align-items: flex-start;'>
<div>计划ID：$id</div>  
<div>计划状态：{$info['plan_state_desc']}</div> 
<div style='padding-left: 10px;'>用户UID: {$info['uid']}</div> 
<div style='padding-left: 10px;'>用户昵称：{$info['nick']}</div>
<div style='padding-left: 10px;'>用户类型：{$info['utype_desc']}</div></div>";

        $content->row($top);

        $form = new Form($info);
        $form->hidden('id', '计划ID');
        $form->text('plan_name', '计划名称')->readonly()->setWidth(6);
        $form->select('ad_type', '投放类型')->options(mAdPlan::AD_TYPE)->setWidth(4)->readonly();
        $form->dateTimeRange('start_time', 'end_time', '投放时间')->setWidth(8)->readonly();
        $form->datetime('settle_time', '结算时间')->setWidth(8)->readonly();
        $form->text('settle_status', '结算状态')->setWidth(4)->readonly();
        $form->display('package_name', '人群包')->setWidth(4);
        $form->text('plan_count', '计划数量')->setWidth(4)->readonly();
        $form->text('target_count', '计划曝光')->setWidth(4)->readonly();
        $form->text('expose_count', '当前曝光')->setWidth(4)->readonly();
        $form->text('finished_rate', '进度完成')->setWidth(4)->readonly();
        $form->text('flow_rate', '真实流量比例')->setWidth(4)->readonly();
        $form->text('real_target_count', '真实计划曝光')->setWidth(4)->readonly();
        $form->text('real_expose_count', '当前真实曝光')->setWidth(4)->readonly();
        $form->currency('price', '购买单价')->setWidth(4)->readonly()->symbol('¥');
        $form->currency('buy_amount', '总金额')->setWidth(4)->readonly()->symbol('¥');
        if ($info['amount'] > 0) {
            $form->currency('amount', '花费金额')->setWidth(4)->readonly()->symbol('¥');
        }
        if ($info['refund_amount'] > 0) {
            $form->currency('refund_amount', '返还金额')->setWidth(4)->readonly()->symbol('¥');
        }
        $form->disableSubmit();
        $form->disableReset();

        $content->row('<div class="box">' . $form->render() . '</div>');

        $stat = "<div class='box' style='padding:20px 20px; display: flex;flex-direction: row; justify-content: space-between; align-items: flex-start;'>
<div>当前曝光：{$info['expose_count']}</div>  
<div>当前真实曝光：{$info['real_expose_count']}</div>  
<div style='padding-left: 10px;'>点击率: {$info['click_rate']} </div> 
<div style='padding-left: 10px;'>点击量：{$info['click_count']}</div>
</div>";

        $content->row(function (Row $row) use ($stat) {
            $row->column(12, function (Column $column) use ($stat) {
                $column->row('<div style="font-weight: 700;padding-bottom: 10px;">计划内容数据</div>');
                $column->row($stat);
            });
        });

        $headers = ['加油包ID', '用户UID', '类型', '加油包编号', '创建时间', '目标曝光量', '当前曝光量'];

        $where = [
            'plan_id' => $id,
            'ORDER' => ['id' => 'ASC'],
        ];

        $rows = mAdPlanDataFlow::dataSelect($where, ['flow_package_id', 'uid', 'type', 'plan_flow_no', 'create_time']);
        $flowPackageIds = array_column($rows, 'flow_package_id');
        $limit = [0, count($flowPackageIds)];
        $flowPackageInfos = $flowPackageIds ? mFlowPackage::getListByAdmin(['id' => $flowPackageIds], $limit) : [];
        $flowPackageInfos = $flowPackageInfos ? array_column($flowPackageInfos, null, 'id') : [];
        $types = [1 => '新建', 2 => '追加'];

        foreach ($rows as $key => $row) {
            $rows[$key]['type'] = $types[$row['type']];
            $rows[$key]['target_exposure'] = $flowPackageInfos[$row['flow_package_id']]['target_exposure'];
            $rows[$key]['real_exposure'] = $flowPackageInfos[$row['flow_package_id']]['real_exposure'];
        }

        $table = new Table($headers, $rows);

        $foot = '<div class="box" >' . $table->render() . '</div>';

        $content->row(function (Row $row) use ($foot) {
            $row->column(12, function (Column $column) use ($foot) {
                $column->row('<div style="font-weight: 700;padding-bottom: 10px;">计划关联流量包</div>');
                $column->row($foot);
            });
        });

        return $content
            ->header('投放计划详情')
            ->breadcrumb(
                ['text' => '投放计划列表', 'url' => url('/admin/BizAd/plan/list')],
                ['text' => '投放计划详情']
            );
    }

    public function ctrWhite(Request $request, Content $content): Content
    {
        $objIds = CtrWhite::getWhite();
        $info['obj_ids'] = $objIds ? implode(',', $objIds) : '';
        $form = new Form($info);
        $form->textarea('obj_ids', '内容id')->help('多个内容id以英文逗号(,)隔开。');
        $form->action(url('/admin/BizAd/plan/ctr/white/save'));
        return $content->row($form)
            ->header('ctr白名单')
            ->breadcrumb(
                ['text' => '投放计划列表', 'url' => url('/admin/BizAd/plan/list')],
                ['text' => 'ctr白名单']
            );
    }

    public function saveCtrWhite(Request $request, Content $content)
    {
        $objIds = $request->input('obj_ids', '');
        $objIds = $objIds ? str_replace(" ", "", trim($objIds)) : '';
        $objIds = $objIds ? str_replace("，", ",", trim($objIds)) : '';
        if ($objIds) {
            $objIds = explode(',', $objIds);
            $objIds = array_filter($objIds);
            CtrWhite::addWhite($objIds);
            $success = new MessageBag([
                'title' => '保存成功'
            ]);
            return redirect('/admin/BizAd/plan/ctr/white')->with(compact('success'));
        } else {
            $error = new MessageBag([
                'title' => '保存失败'
            ]);
            return back()->with(compact('error'));
        }
    }

    public function rateList(Request $request, Content $content): Content
    {
        $rateList = mAdPlanFlowRate::getList(['status' => mAdPlanFlowRate::STATUS_NORMAL, 'ORDER' => ['uid' => 'ASC']]);
        $uids = $rateList ? array_column($rateList, 'uid') : [];
        $userList = $uids ? User::getBatchBasicUserInfo($uids) : [];
        $userList = $userList ? array_column($userList, null, 'uid') : [];
        $brandUids = [];
        foreach ($userList as $item) {
            if ($item['type'] == Member::AUTH_USER_BRAND) {
                $brandUids[] = $item['uid'];
            }
        }

        $brandInfos = $brandUids ? Brand::selectNormalBrandsByUid($brandUids) : [];
        $brandInfos = $brandInfos ? array_column($brandInfos, null, 'uid') : [];
        $list = [];
        foreach ($rateList as $row) {
            $userInfo = $userList[$row['uid']] ?? [];
            $brandInfo = $brandInfos[$row['uid']] ?? [];
            $row['nick'] = $userInfo['nick'] ?? '-';
            $row['type'] = $userInfo['type'] ?? null;
            $row['brand_id'] = $brandInfo ? $brandInfo['id'] : '';
            $row['brand_name'] = $brandInfo ? $brandInfo['brand_name'] : '';
            $list[] = $row;
        }
        $gridModel = new GridDataModel($list);
        $grid = Admin::grid($gridModel, function (Grid $grid) use ($gridModel) {
            $grid->disableFilter();
            $grid->disablePagination();
            $grid->tools(function (Grid\Tools $tools) {
                $tools->append('<div class="btn-group download" style="margin-right: 10px">
    <a class="btn btn-sm btn-warning" href="javascript:layer.open({
                                type: 2,
                                title: \'编辑\',
                                maxmin: true,
                                shadeClose: true,
                                shade: 0,
                                area: [\'750px\', \'500px\'],
                                content: \'/admin/BizAd/plan/rate/list/create?uid=0\'
                            });" title="新增通用设置"><i class="fa"></i><span class="hidden-xs">新增通用设置</span></a>
</div>');
                $tools->append('<div class="btn-group download" style="margin-right: 10px">
    <a class="btn btn-sm btn-twitter"  href="javascript:layer.open({
                                type: 2,
                                title: \'编辑\',
                                maxmin: true,
                                shadeClose: true,
                                shade: 0,
                                area: [\'750px\', \'500px\'],
                                content: \'/admin/BizAd/plan/rate/list/create\'
                            });" title="新增用户设置"><i class="fa"></i><span class="hidden-xs">新增用户设置</span></a>
</div>');
            });

            $grid->disableCreateButton();
            $grid->disableRowSelector();
            $grid->disableExport();
            $grid->column('id', 'ID');
            $grid->column('uid', 'uid')->display(function () {
                if ($this->uid == 0) {
                    return '通用设置';
                } else {
                    return $this->uid;
                }
            });
            $grid->column('nick', '昵称');
            $grid->column('type', '用户身份')->display(function () {
                if (!is_null($this->type)) {
                    if ($this->type == Member::AUTH_USER_BRAND) {
                        $html = '<ul class="list-unstyled">';
                        $html .= '<li>品牌id:' . $this->brand_id . '</li>';
                        $html .= '<li>品牌名称:' . $this->brand_name . '</li>';
                        $html .= '</ul>';
                        return $html;
                    }
                    return Member::$typeDesc[$this->type];
                }
                return '-';
            });
            $grid->column('flow_rate', '真实流量比例');
            $grid->column('edittime', '更新时间');
            $grid->column('admin_id', '操作人')->display(function () {
                if (!$this->admin_id) {
                    return '-';
                } else {
                    return Admin::user()->find($this->admin_id)->name;
                }
            });
            $grid->disableExport();
            $grid->disableRowSelector();
            $grid->actions(function (Grid\Displayers\Actions $actions) {
                if ($actions->row->uid == 0) {
                    $actions->disableDelete();
                }
                $actions->disableEdit();
                $url = '/admin/BizAd/plan/rate/list/' . $actions->row->id . '/edit?uid=' . $actions->row->uid;
                $actions->append('<a class=" fa fa-edit" href="javascript:layer.open({
                                type: 2,
                                title: \'编辑\',
                                maxmin: true,
                                shadeClose: true,
                                shade: 0,
                                area: [\'750px\', \'500px\'],
                                content: \'' . $url . '\'
                            });
               ">编辑</a><br/>');
            });
        });
        return $content->row($grid)
            ->header('CPM真实流量比例控制')
            ->breadcrumb(
                ['text' => '投放计划列表', 'url' => url('/admin/BizAd/plan/list')],
                ['text' => 'CPM真实流量比例控制']
            );
    }


    public function rateEdit(Request $request, WorkContent $content, $id = 0)
    {
        $code = $request->input('code', 0);
        $uid = $request->get('uid');
        if ($code == 1) {
            $script = <<<SCRIPT
            setTimeout(function () {
                        parent.window.location.reload();
                    }, 10);
SCRIPT;
            Admin::script($script);
        }
        if ($id > 0) {
            $info = mAdPlanFlowRate::getInfoById($id);
            $uid = $info['uid'];
            $info['admin_name'] = $info['admin_id'] ? Admin::user()->find($info['admin_id'])->name : '-';
        } else {
            $info = [];
        }
        $form = new Form($info);
        $form->hidden('id');
        if (!is_null($uid) && $uid == 0) {
            $title = '通用流量比例设置';
            $form->hidden('uid');
        } else {
            $title = '用户流量比例设置';
            $form->text('uid', '用户uid')->required();
        }
        $form->decimal('flow_rate', '真实流量比例')->required()->help('请输入0.1~1之间的数，小数保留一位。');
        $form->datetime("edittime", '上次更新时间')->readonly();
        $form->text("admin_name", '最后操作人')->readonly();
        $form->action('/admin/BizAd/plan/rate/list/save');
        return $content->header($title)
            ->row($form);
    }

    public function rateSave(Request $request)
    {
        $params = $request->all();
        $id = $params['id'] ?? 0;
        $uid = $params['uid'] ?? 0;
        $rate = $params['flow_rate'] ?? 0;
        $rate = bcadd($rate, 0, 1);
        try {
            if ($rate > 1 || $rate < 0.1) {
                throw new \Exception('真实流量比例:请输入0.1~1之间的数，小数保留一位！');
            }
            if (!is_numeric($rate)) {
                throw new \Exception('真实流量比例:请输入0.1~1之间的数，小数保留一位！');
            }
            $data = [
                'uid' => $uid,
                'flow_rate' => $rate,
                'status' => mAdPlanFlowRate::STATUS_NORMAL,
                'admin_id' => Admin::user()->id,
            ];
            if ($id) {
                $res = mAdPlanFlowRate::updateData($id, $data);
            } else {
                $info = mAdPlanFlowRate::getInfo($uid);
                if ($info) {
                    $res = mAdPlanFlowRate::updateData($info['id'], $data);
                } else {
                    $res = mAdPlanFlowRate::addData($data);
                }
            }
            if ($res) {
                $success = new MessageBag([
                    'title' => '保存成功'
                ]);
            } else {
                $error = new MessageBag([
                    'title' => '保存失败'
                ]);
                return back()->withInput()->with(compact('error'));
            }
            return redirect("admin/BizAd/plan/rate/list/create?code=1")->with(compact('success'));
        } catch (\Exception $e) {
            $error = new MessageBag([
                'title' => '保存失败,' . $e->getMessage()
            ]);
            return back()->withInput()->with(compact('error'));
        }
    }

    public function rateDel(Request $request, $id = 0)
    {
        mAdPlanFlowRate::updateData($id, ['status' => mAdPlanFlowRate::STATUS_DELETE, 'admin_id' => Admin::user()->id]);
        $success = [
            'title' => '删除成功',
            'code' => 0,
            'status' => false,
        ];
        return response()->json($success);
    }

    public function planContentTag(Request $request, $id)
    {
        try {
            $id = $request->input('id', 0);
            $info = mAdPlan::getPlanInfo($id);
            $objId = $info['obj_id'];
            if (empty($objId)) {
                throw new \Exception('不存在内容');
            }
            $contentSignExtendinfo = $objId ? ContentSignExtend::getExtendInfoByNoteIds($objId) : [];

            $data = [
                "obj_id" => $objId,
                "is_display_business" => ContentSignExtend::IS_BUSINESS,
                "admin_id" => Admin::user()->id,
                "obj_type" => IdParse::getType($objId),
                'edittime' => date('Y-m-d H:i:s'),
            ];
            if ($contentSignExtendinfo) {
                $rs = ContentSignExtend::upateExtendInfo($data, ['obj_id' => $id]);
            } else {
                $data["addtime"] = date('Y-m-d H:i:s', time());
                $rs = ContentSignExtend::addExtendInfo($data);
            }
            if (!$rs) {
                throw new \Exception('打标失败');
            }

            $result = [
                'title' => '打标成功',
                'code' => 1,
            ];
        } catch (\Exception $e) {
            $result = [
                'title' => $e->getMessage(),
                'msg' => '信息：' . $e->getFile() . $e->getLine(),
                'code' => 0,
                'status' => false,
            ];
        }

        return response()->json($result);
    }


    public function priceList(Request $request, Content $content): Content
    {
        $requestAll = $request->all();

        $list = mAdPrice::getAllPrice();

        $userPackageOption = mAdPrice::getUserPackageMap();

        $gridModel = new GridDataModel($list);
        $grid = Admin::grid($gridModel, function (Grid $grid) use ($gridModel, $userPackageOption) {
            $grid->disablePagination();
            $grid->disableFilter();
            $grid->disableRowSelector();
            $grid->disableExport();
            $grid->column('id', 'ID');
            $grid->column('package', '人群包')->display(function () use ($userPackageOption) {
                if ($userPackageOption) {
                    return $userPackageOption[$this->package];
                } else {
                    return '未获取到';
                }
            });
            $grid->column('package_name', '人群包名称');
            $grid->column('package_desc', '人群包描述');
            $grid->column('original_price', '单价（原价）');
            $grid->column('price', '单价（优惠价）');
            $grid->column('count', '总量');
            $grid->column('total_price', '总价');
            $grid->column('create_time', '创建时间');
            $grid->column('update_time', '更新时间');
            $grid->column('admin_id', '操作人')->display(function () {
                if (!$this->admin_id) {
                    return '-';
                } else {
                    return Admin::user()->find($this->admin_id)->name;
                }
            });
            $grid->actions(function (Grid\Displayers\Actions $actions) {
                $actions->disableDelete();
            });
        });

        $content->row($grid);

        return $content
            ->header('投放计划价格配置')
            ->breadcrumb(
                ['text' => '投放计划列表', 'url' => url('/admin/BizAd/plan/list')],
                ['text' => '投放计划价格配置']
            );
    }

    public function priceInfo(Request $request, Content $content, $id = 0): Content
    {
        $info = $id ? mAdPrice::getInfoById($id) : [];
        $userPackageOption = mAdPrice::getUserPackageMap();
        if (empty($userPackageOption)) {
            return $content->row('未获取到人群包信息');
        }
        $form = new Form($info);
        $form->hidden('id', 'id');
        $form->select('package', '人群包')->options($userPackageOption)->setWidth(4)->required();
        $form->text('package_name', '人群包名称')->setWidth(6)->required();
        $form->text('package_desc', '人群包描述')->setWidth(6)->required();
        $form->decimal('original_price', '单价（原价）')->setWidth(6)->required();
        $form->decimal('price', '单价（优惠价）')->setWidth(6)->required();
        $form->radio('count', '数量')->setWidth(4)->options([50 => 50, 100 => 100])->default(50)->required();
        $form->decimal('total_price', '总价')->setWidth(4)->required();
        $form->action(url('/admin/BizAd/plan/price/save'));

        return $content->row($form)
            ->header('投放计划价格配置')
            ->breadcrumb(
                ['text' => '投放计划价格配置', 'url' => url('/admin/BizAd/plan/price/list')],
                ['text' => '投放计划价格配置']
            );
    }

    public function savePrice(Request $request, Content $content)
    {
        try {
            $requestAll = $request->all();
            $id = $requestAll['id'] ?? 0;
            $data = [
                'package' => $requestAll['package'] ?? 0,
                'package_name' => trim($requestAll['package_name']) ?? '',
                'package_desc' => trim($requestAll['package_desc']) ?? '',
                'original_price' => $requestAll['original_price'] ?? 0,
                'price' => $requestAll['price'] ?? 0,
                'count' => $requestAll['count'] ?? 0,
                'total_price' => $requestAll['total_price'] ?? 0,
                'admin_id' => Admin::user()->id,
                'price_status' => mAdPrice::PRICE_STATUS_NORMAL
            ];
            if (bccomp(bcmul($data['price'], $data['count'], 2), $data['total_price'], 2) != 0) {
                throw new \Exception('计算总价错误');
            }
            if ($data['count'] > 0 && $data['total_price'] > 0) {
                if ($id) {
                    $data['update_time'] = date('Y-m-d H:i:s');
                    $res = mAdPrice::dataUpdate($data, ['id' => $id]);
                } else {
                    $data['create_time'] = date('Y-m-d H:i:s');
                    $data['update_time'] = date('Y-m-d H:i:s');
                    $res = mAdPrice::dataInsert($data);
                }
                if (!$res) {
                    throw new \Exception('操作数据失败');
                }
            } else {
                throw new \Exception('价格配置错误');
            }
            $success = new MessageBag([
                'title' => '保存成功'
            ]);
            return redirect('/admin/BizAd/plan/price/list')->with(compact('success'));
        } catch (\Exception $e) {
            $error = new MessageBag([
                'title' => '保存失败,' . $e->getMessage()
            ]);
            return back()->with(compact('error'));
        }
    }


}